<template>
  <div class="statistics-container">
    <el-table :data="tableParams.rows">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="状态" prop="name" width="55" fixed="left">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>

          <div v-else class="status-icon">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column label="姓名" prop="user_Info.baseInfo.name" width="80" />
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row.user_Info.baseInfo.identityCard) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="user_Info.baseInfo.mobile"
        label="联系方式"
        width="120"
      />
      <el-table-column
        prop="user_Info.baseInfo.identityCard"
        label="身份证号"
        width="180"
      />
      <el-table-column label="报名所属" width="120" show-overflow-tooltip>
        <template #default="scope">
          {{ affiliation_format(scope.row.user_Info.baseInfo.affiliation) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="user_Info.baseInfo.enterprise"
        label="所在企业名称"
        width="250"
        show-overflow-tooltip
      />
      <el-table-column
        prop="declarationBatchNumber"
        label="申请批次号"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column label="签到情况">
        <template #default="scope">
          {{ (scope.row.signIn_data && scope.row.signIn_data.length) || 0 }} /
          {{ denominator(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="签到率">
        <template #default="scope">
          <div v-if="!denominator(scope.row)">0%</div>
          <div v-else>
            {{
              Math.round(
                (((scope.row.signIn_data && scope.row.signIn_data.length) ||
                  0) /
                  denominator(scope.row)) *
                  100
              )
            }}%
          </div>
        </template>
      </el-table-column>
      <el-table-column label="获证情况" width="100">
        <template #default="scope">
          <div v-if="scope.row.hasOwnProperty('isExamination')">
            {{ scope.row.isExamination == 1 ? "获证" : "未获证" }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="理论成绩" prop="theory" />
      <el-table-column label="实训成绩" prop="practicalTraining" />
      <el-table-column
        label="进班日期"
        align="center"
        width="160"
        fixed="right"
      >
        <template #default="scope">
          {{ proxy.$utils.dateTimeFormateFn(scope.row._add_time, "all") }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="tableParams['total']"
      :total="tableParams['total']"
      v-model:page="formInline.pageIndex"
      v-model:limit="formInline.pageSize"
      @pagination="getInfo"
    />
  </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
let props = defineProps(["info", "type"]);

let tableParams = ref({});
let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  classId: "",
  keyWords: "",
  screen: 1,
});
let allTeachingSchedule = ref([]);
let templateUrl;

async function getInfo() {
  formInline.value.classId = props.info._id;
  await getScheduleDate();
  tableParams.value = await proxy.$apis.classStudent({
    type: "list",
    data: formInline.value,
  });
}

async function getScheduleDate() {
  //全部排课
  let arr = await proxy.$apis.teachingScheduleData({
    type: "query",
    data: { classId: props.info._id },
  });
  let teachers = [];
  arr.forEach((element) => {
    teachers.push(element.teachingTeacher);
  });
  allTeachingSchedule.value = [...arr];
}

function denominator(row) {
  //如果有停课日期
  if (row.suspensionClassDate) {
    let time = proxy.$utils.getTimeFn(row.suspensionClassDate);
    let arr = [];
    allTeachingSchedule.value.forEach((element) => {
      if (time > element.dateStamp) {
        arr.push(element.dateStamp);
      }
    });
    return arr.length;
  } else {
    return allTeachingSchedule.value.length;
  }
}

function getGenderByIdCard(idCard) {
  if (!idCard || idCard.length !== 18) {
    throw new Error("Invalid ID card number");
  }
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

function affiliation_format(e) {
  if (!e) return "-";
  if (proxy.$utils.isString(e)) {
    return e;
  } else if (proxy.$utils.isArrayOrJsonArray(e)) {
    return e.toString();
  } else {
    return "-";
  }
}

async function exportWord() {
  if (!templateUrl) return proxy.$utils.showToast("请先设置模板");
  let resp = await counter.trainingResultExportParams(props.info._id);
  let url = await proxy.$apis.classDocExport({
    templateURL: templateUrl,
    data: {
      numberRegistrations: resp.numberRegistrations, //注册人数
      attendance: resp.attendance, //出勤率
      certifiedNum: resp.certifiedNum, //获证人数
      quaRate: resp.quaRate, //培训合格率
      numberAppraisers: resp.numberAppraisers, //鉴定人数
      qualificationRate: resp.qualificationRate, //鉴定合格率
    },
    fileName: "培训结果统计表.docx",
  });
  window.location.href = url;
}

function downLoadTemplate() {
  window.location.href = templateUrl;
}

async function getTemplateUrl() {
  templateUrl = await proxy.$apis.fileTemplate({
    data: { type: props.type },
    type: "downLoad",
  });
}

watch(
  () => [props.info],
  (newValue, oldValue) => {
    if (newValue) {
      getInfo();
      getTemplateUrl();
    }
  },
  { deep: true, immediate: true }
);

defineExpose({ exportWord, downLoadTemplate, getTemplateUrl });
</script>

<style lang="scss" scoped>
.status-icon {
  width: 15px;
  height: 15px;
  img {
    width: 100%;
    display: block;
  }
}
</style>
